<?php
	class UsersController extends AppController{
		var $name = 'Users';
		var $helpers = array('Html','Javascript');
		var $uses = array('User','HandHistory');
		
		function index(){
		}
		
		function login(){
			
			if(isset($this->data)){
				//debug($this->data);
				$_SESSION['username'] = $this->data['User']['username'];
				$this->redirect('/users/home');
				exit();
			}
			
		}

		
		function home(){
			
			if(!isset($_SESSION['username'])){
				$this->redirect('/');
				exit();
			}
			
			$monthHandsSeen ='';
			$monthVPP ='';
			$monthPFR ='';
			$afTotal = '';
			$afRaise = '';
			$afBet ='';
			$afCall = '';
			$wtsd ='';
			$wtsdw ='';
			$textFilesToProcess = array();
			
	$userdir = isset($_SESSION['username']) ? './userfiles/'.$_SESSION['username'] : './userfiles/ron0914';
	$dirList = $this->User->ReadFolderDirectory($userdir);
	$dates = array_keys($dirList);
	
	//echo '<pre>'; print_r($dirList); echo '</pre>';
	/*
	var events = [
    { "EventID": 1, "StartDate": new Date(2009, 1, 12), "Title": "10:00 pm - EventTitle1", "URL": "#", "Description": "This is a sample event description", "CssClass": "Birthday" },
    { "EventID": 2, "Date": "2009-02-28T00:00:00.0000000", "Title": "9:30 pm - this is a much longer title", "URL": "#", "Description": "This is a sample event description", "CssClass": "Meeting" },
];
	*/
	
	//debug('username is '.$_SESSION['username']);
	if(isset($_SESSION['username'])){
		//echo 'Cache version number is '.$HandHistory->cacheVersion;
	$eventsJsonString = '[';
	foreach($dates as $key=>$date){
		$year = date('Y',strtotime($date));
		$month = date('m',strtotime($date))-1; //stupid javascript month from 0
		$day = date('d',strtotime($date));
		
		//echo $date;
		//watch for pokerstars email hand history text files
		if(!is_array($dirList[$date])){
			$textFilesToProcess[] = $dirList[$date];
			continue;
		}
		
		foreach($dirList[$date] as $id=>$table){
			if(substr($table,0,1) != "."){
				$eventClass = 'notProcessed';
				//is there a cache of hand information?
				$md5File = md5_file($userdir.'/'.$date.'/'.$table);
				if(file_exists($userdir.'/'.$date.'/.'.$md5File.'.txt')){
					
					$handLog = file_get_contents($userdir.'/'.$date.'/.'.$md5File.'.txt');
					$handLog = unserialize($handLog);
					if(isset($handLog['version']) && $handLog['version']
							==
						$this->HandHistory->getCacheVersion()){
						//get the event class
						//echo '<pre>'; print_r($handLog); echo '</pre>';
						//$eventClass = ($handLog['tableStats']['roi'] < 0 ) ? 'lost' : 'won';
						$eventClass = $this->HandHistory->calculateTableCssClass($handLog);
						$monthHandsSeen += $handLog['tableStats']['handsSeen'];
						$monthVPP += $handLog['tableStats']['vpp'];
						$monthPFR += $handLog['tableStats']['pfr'];
						
						$afTotal += $handLog['tableStats']['agression']['raise']+$handLog['tableStats']['agression']['bet']+$handLog['tableStats']['agression']['call'];
						$afRaise += $handLog['tableStats']['agression']['raise'];
						$afBet += $handLog['tableStats']['agression']['bet'];
						$afCall += $handLog['tableStats']['agression']['call'];
						
						
					$wtsd += $handLog['tableStats']['wtsd'];
					$wtsdw += $handLog['tableStats']['wtsdw'];
						//cash is roi positive
						//stt - is finishing position in the money
					}
					else{
						//version is out of date unlink the file
						@unlink($userdir.'/'.$date.'/.'.$md5File.'.txt');
					}
					//echo '<pre>'; 
						//print_r($handLog);
					//echo '</pre>';
				}
				
		$event = '{ "EventID" : '.($id+1).', "StartDate" : new Date('.$year.', '.$month.', '.$day.'), "Title": "'.str_replace('.txt','',$table).'", "URL" : "/hand_history/view?date='.$date.'&table='.urlencode($table).'", "Description" : "'.str_replace('.txt','',$table).'", "CssClass" : "'.$eventClass.'"},';
		$eventsJsonString .= $event;
				if(!isset($lastEventTimeStamp) || strtotime($date)>$lastEventTimeStamp){
					$lastEventDate = ' new Date('.$year.', '.$month.', '.$day.')';
					$lastEventTimeStamp = strtotime($date);
				}
			}
		}
		
	}
	//drop the last comma
	$eventsJsonString = substr($eventsJsonString,0,-1);
	
	foreach($textFilesToProcess as $key=>$textFile){
		@$fp = fopen($userdir.'/'.$textfile,'r');
		if($fp){
			//process the text file - save each hand cache file in the correct date folder
		
		fclose($fp);
		}
		
	}
	
	$eventsJsonString .= ']';
	
	}
	$this->set('eventsJsonString',$eventsJsonString);
	
	if(isset($_REQUEST['date'])){
		$year = date('Y',strtotime($_REQUEST['date']));
		$month = date('m',strtotime($_REQUEST['date']))-1; //stupid javascript month from 0
		$day = date('d',strtotime($_REQUEST['date']));
		$lastEventDate =' new Date('.$year.', '.$month.', '.$day.')';		
	}
	$this->set('lastEventDate',$lastEventDate);
	
	//debug($lastEventDate);
	
				
			$this->set('monthHandsSeen',$monthHandsSeen);
			$this->set('monthVPP',$monthVPP);
			$this->set('monthPFR',$monthPFR);
			$this->set('afTotal',$afTotal);
			$this->set('afRaise',$afRaise);
			$this->set('afBet',$afBet);
			$this->set('afCall',$afCall);
			$this->set('wtsd',$wtsd);
			$this->set('wtsdw',$wtsdw);
	
		}
		
		
		function register(){
			$this->data = $_POST['data'];
			if(!empty($this->data)){
				
			}
		}
		
		function uploadHandHistory(){
		}
		
		function logout(){
			unset($_SESSION['username']);
			$this->redirect('/');
				exit();
		}
		
		function uploadHands(){
			if(!isset($_SESSION['username'])){
				$this->Session->setFlash('Your login has expired.');
				$this->redirect('/');
			}
			if(!empty($this->data)){
				//debug($this->data['HandHistory']['archive']);
				//archive must be tar or zip
				$extension = explode('.',$this->data['HandHistory']['archive']['name']);
				if($extension[1] == 'zip'){
					//extract the archive to the userfiles directory
					$extract = 'unzip '.$this->data['HandHistory']['archive']['tmp_name'].' -d ./userfiles/';
				}
				if($extension[1] == 'tar'){
					$extract = 'tar -xvf '.$this->data['HandHistory']['archive']['tmp_name'].' -C userfiles';
				}
				
				exec($extract);
				$this->redirect('/users/home');
			}
			exit();
		}
		
	}
?>